<template>
    <el-select
        ref="selectRef"
        v-bind="$attrs"
    >
        <!-- eslint-disable-next-line -->
        <el-option
            v-for="item in options"
            v-bind="computedTransOptions(item)"
        >
            <template v-if="option || $slots.option">
                <BaseRender v-if="option" :render="option" :item="item"></BaseRender>
                <slot v-else name="option" :item="item"></slot>
            </template>
        </el-option>
        <template #prefix v-if="prefix || $slots.prefix">
            <BaseRender v-if="prefix" :render="prefix"></BaseRender>
            <slot v-else name="prefix"></slot>
        </template>
        <template #empty v-if="empty || $slots.empty">
            <BaseRender v-if="empty" :render="empty"></BaseRender>
            <slot v-else name="empty"></slot>
        </template>
    </el-select>
</template>

<script setup>
import { computed, ref, useAttrs } from 'vue'
const selectRef = ref(null)
const props = defineProps({
    options: {
        type: Array,
        default: () => []
    },
    transOptions: {
        type: Function
    },
    labelField: {
        type: String
    },
    valueField: {
        type: String
    },
    option: {
        type: Function
    },
    prefix: {
        type: Function
    },
    empty: {
        type: Function
    }
})

const defaultTransOptions = option => {
    const { value, label, disabled, ...args } = option
    return {
        key: value,
        value,
        label,
        disabled
    }
}

const objTransOptions = option => {
    return {
        key: option[attrs.valueKey] || option[attrs['value-key']] || option.value,
        value: option,
        label: option.label
    }
}

const presetKeyOptions = option => {
    return {
        key: option[props.valueField],
        label: option[props.labelField],
        value: option[props.valueField],
        disabled: option.disabled
    }
}

const computedTransOptions = computed(() => {
    if (props.labelField && props.valueField) return presetKeyOptions
    if (props.transOptions) return props.transOptions
    if (attrs.valueKey || attrs['value-key']) return objTransOptions
    return defaultTransOptions
})

const attrs = useAttrs()

defineExpose({
    selectRef
})
</script>

<style lang="scss" scoped>

</style>